import json
from asgiref.sync import async_to_sync
from channels.generic.websocket import WebsocketConsumer

from .models import ChatRoomModel, ChatMessageModel
from myapp.models import User, Merchant

# 固定方法
class ChatConsumer(WebsocketConsumer):
    # 接收房间号
    def connect(self):
        self.room_name = self.scope['url_route']['kwargs']['room_name']
        self.room_group_name = 'chat_%s' % self.room_name
        print('接收到的消息1', self.room_name)
        print('接收到的消息2', self.room_group_name)
        # Join room group
        async_to_sync(self.channel_layer.group_add)(
            self.room_group_name,
            self.channel_name
        )

        self.accept()
    #     将接收到的房间号  加入数据库
        room = ChatRoomModel.objects.filter(room_name=self.room_name).first()
        if not room:  # 没有房间号 存入数据库
            try:
                data = ChatRoomModel.objects.create(room_name=self.room_name)
                data.save()
            except Exception as e:
                print(f'房间存库失败{e}')
                return '房间存库失败'


    #  断开连接
    def disconnect(self, close_code):
        # Leave room group
        async_to_sync(self.channel_layer.group_discard)(
            self.room_group_name,
            self.channel_name
        )

    #  接收到前端发送的消息  前端组织
    def receive(self, text_data):

        text_data_json = json.loads(text_data)
        print('接收到的消息3', text_data_json)
        message = text_data_json['message']
        uid = text_data_json['uid']
        mid = text_data_json['mid']
        types = text_data_json['types']
        room = text_data_json['room']
        # 存入数据库
        print('接收到的消息3', text_data_json)

        if types == 0:
            user = User.objects.get(id = uid)
            text_data_json['username'] = user.account
            text_data_json['uid'] = user.id
        if types == 1:
            merchant = Merchant.objects.get(id = mid)
            text_data_json['mname'] = merchant.username
            text_data_json['mid'] = merchant.id
        romm_id = ChatRoomModel.objects.filter(room_name=room).first()
        comm = romm_id.id
        print('comm>>>', comm)

        ChatMessageModel.objects.create(user_id=uid, merchant_id=mid, message=message, types=types, room_id=comm)

        text_data_json["type"] = "chat_message"
        # Send message to room group
        async_to_sync(self.channel_layer.group_send)(
            self.room_group_name,
            # 返回给前端的数据 自己组织
            text_data_json,
        )

    # 将接收到的数据展示到前端框里
    def chat_message(self, event):
        # message = event['message']

        print('发给消息', event)
        self.send(text_data=json.dumps(event))
